﻿using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;//日志记录
using System.Diagnostics;//秒表

namespace ApiServer.Middelware
{
    //自定义日志中间件 实现了点击某个方法，控制台输出执行该方法的时间
    public class LogMiddelware
    {
        //下一个请求委托
        private readonly RequestDelegate next;
        private readonly ILogger<LogMiddelware> logger;
        /// <summary>
        /// 构造方法进行依赖注入
        /// </summary>
        /// <param name="next"></param>
        /// <param name="logger"></param>
        public LogMiddelware(RequestDelegate next, ILogger<LogMiddelware> logger)
        {
            this.next = next;
            this.logger = logger;
        }
        /// <summary>
        /// 公开方法
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public async Task InvokeAsync(HttpContext context)
        {
            Stopwatch stopwatch = Stopwatch.StartNew();
            stopwatch.Start();
            await next(context);
            stopwatch.Stop();

            string requestUrl = context.Request.Path;
            logger.LogInformation($"请求{requestUrl},消耗了{stopwatch.ElapsedMilliseconds}毫秒");
        }
    }
}
